import { InUrlModel } from '../dbs/in_url';
import { OutUrlModel } from '../dbs/out_url';
import { EmailModel } from '../dbs/emails_urls'
/**
 * 存储到数据库中，异步模型，返回一个promise
 * @param data
 */
export function save_inurl(data) {
    for (var key in data) {
        if (isEmpty(data[key])) {
            delete data[key];
        }
    }
    const inurl_model = new InUrlModel(data);
    return inurl_model.save();
}

export function save_outurl(data) {
    for (var key in data) {
        if (isEmpty(data[key])) {
            delete data[key];
        }
    }
    const outurl_model = new OutUrlModel(data);
    return outurl_model.save();
}

export function update_inurl(condition, data) {
    if (data.createTime) {
        data.createTime = new Date(data.createTime).getTime();
    }
    if (data.successTime)
        data.successTime = new Date(data.successTime).getTime();
    return InUrlModel.update(condition, data).exec();
}

export function update_outurl(condition, data) {
    if (data.createTime) {
        data.createTime = new Date(data.createTime).getTime();
    }
    return OutUrlModel.update(condition, data).exec();
}

export function find_inurl(condition={}) {
    return InUrlModel.find(condition).exec()
}

export function find_outurl(condition={}) {
    return OutUrlModel.find(condition).exec();
}

export function inactive_outurl(id) {
    return OutUrlModel.update({_id:id}, {status:0}).exec();
}

export function inactive_inurl(id) {
    return InUrlModel.update({_id:id}, {status:0}).exec();
}

export function email_url_list(condition={status: {$gte:0}}) {
    return EmailModel.find(condition, {}).sort({status:1}).exec();
}

export function use_email(id) {
    return EmailModel.update({_id:id}, {$inc:{status:1}, $set:{createTime:Date.now()}}).exec();
}

export function finish_email(id) {
    return EmailModel.update({url:url}, {status:3}).exec();
}

export function del_email(id) {
    return EmailModel.update({_id:id}, {status:-1}).exec();
}

function isEmpty(str) {
    str = str + '';
    str = str.replace(/(^\s*)|(\s*$)/, '');
    if (str)
        return false
    return true;
}